﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Common;

namespace DataLayer
{
    public static class DatPostnetBeneficiario
    {
        public static bool updateBeneficiario(int idBeneficiario, List<int> listPostnets)
        {
            List<Util.DBParameter> parameters = new List<Util.DBParameter>();

            Util.DBParameter pIB;
            pIB.dbType = System.Data.DbType.Int32;
            pIB.parameterName = "@IdBeneficiario";
            pIB.value = idBeneficiario;

            Util.DBParameter pQuery = getQueryUnion(idBeneficiario, listPostnets);

            parameters.Add(pQuery);
            parameters.Add(pIB);
   
            try
            {
                Util.SQLCommandBuild("PostnetBeneficiarioUpdate", parameters).ExecuteNonQuery();
                return true;
            }
            catch (Exception ex)
            {
                Console.WriteLine("error{0}", ex.Message);
                return false;
            }
        }

        public static bool setBeneficiarioPostnet(int idBeneficiario, List<int> listPostnets)
        {

            Util.DBParameter pQuery = getQueryUnion(idBeneficiario, listPostnets);
            
            try
            {
                Util.SQLCommandBuild("PostnetBeneficiarioInsert", pQuery).ExecuteNonQuery();
                return true;
            }
            catch (Exception ex)
            {
                Console.WriteLine("error{0}", ex.Message);
                return false;
            }
        }
        
        private static Util.DBParameter getQueryUnion(int idBeneficiario, List<int> listPostnets)
        {
            StringBuilder sbSelect = new StringBuilder();
            sbSelect.Append("(");
            for (int i = 0; i < listPostnets.Count; i++)
            {
                sbSelect.Append("(SELECT ");
                sbSelect.Append(listPostnets[i]);
                sbSelect.Append(", ");
                sbSelect.Append(idBeneficiario);
                sbSelect.Append(") ");
                if (i != listPostnets.Count - 1)
                {
                    sbSelect.Append("UNION ");
                }
            }
            sbSelect.Append(")");
            Util.DBParameter pQuery;
            pQuery.dbType = System.Data.DbType.String;
            pQuery.parameterName = "@QueryUnions";
            pQuery.value = sbSelect.ToString();

            return pQuery;
        }
    }
}
